package com.ljh.account.Interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljh.account.utils.Response;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

//登录拦截器，拦截所有需要登录的接口，到这里去判断session
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前请求的 Session
        HttpSession session = request.getSession(false); // 不创建新的 Session
        // 检查 Session 是否存在以及是否包含用户信息
        if (session == null || session.getAttribute("username") == null) {
            // 如果没有登录，返回401或重定向到登录页
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            ObjectMapper objectMapper = new ObjectMapper();
            String jsonResponse = objectMapper.writeValueAsString(Response.error("请登录！"));

            response.getWriter().write(jsonResponse);
            return false; // 拦截请求
        }
        Object username = session.getAttribute("username");
        Object userId = session.getAttribute("userId");
        Object accountType = session.getAttribute("accountType");
        request.setAttribute("username", username);
        request.setAttribute("userId", userId);
        request.setAttribute("accountType", accountType);
        return true; // 继续处理请求
    }
}